require 'yaml'

class Event < ActiveRecord::Base
  class InvalidNextState < Exception ; end
  
  has_many :availabilities, :dependent => :destroy
  has_many :attendances, :dependent => :destroy
  has_many :comments, :dependent => :destroy
  
  validates_presence_of :name
  validates_presence_of :description
  validates_numericality_of :required_volunteers
  
  def switch(next_state)
    if next_states.member? next_state
      self.state = next_state
    else
      raise InvalidNextState, "#{next_state} is not a valid next state for an event in state #{state}"
    end
  end
  
  def next_states
    return Event.state_map[state]
  end
  
  def people_template
    
  end
  
  def self.state_map
    s = state_structure
    m = {}
    s.each do |entry|
      m.merge!(entry)
    end
    m
  end
  
  def self.all_states(user)
    user.manager? ? state_structure.map{|entry|entry.keys.first} : %w(cfw assigned)
  end
  
  def self.state_structure
    YAML::load(File.read(File.dirname(__FILE__) + '/../../config/event_states.yml'))
  end
  
  def should_show_to?(user)
    user.manager? || state == 'cfw' || !attendances.find(:first, :conditions => ['user_id=?', user.id]).nil?
  end
  
  def interested_users
    attendances.find(:all, :conditions => ['state=?', 'assigned']).map{|attendance|attendance.user}
  end
  
  def volunteer_count
    availabilities.size
  end
  
  
  def assigned_count
    attendances.size
  end
  
end
